from app import app, db, User, Post, Category, Book, Circle, Notification, Comment
import os

# 删除现有数据库文件
db_path = 'instance/database.db'
if os.path.exists(db_path):
    os.remove(db_path)
    print(f"删除现有数据库: {db_path}")

# 创建数据库表
with app.app_context():
    db.create_all()
    print("创建数据库表完成")
    
    # 创建管理员账户
    admin = User(
        student_id='admin',
        username='管理员',
        is_admin=True,
        is_teacher=True
    )
    admin.set_password('admin123')
    db.session.add(admin)
    
    # 创建默认分类
    categories = [
        Category(name='计算机科学', description='计算机科学与技术相关书籍'),
        Category(name='文学小说', description='文学、小说、散文等作品'),
        Category(name='历史', description='历史类书籍'),
        Category(name='科学', description='科学类书籍'),
        Category(name='艺术', description='艺术类书籍')
    ]
    db.session.add_all(categories)
    
    # 提交更改
    db.session.commit()
    print("初始数据创建完成")
    
    # 验证 Post 表结构
    from sqlalchemy import inspect
    inspector = inspect(db.engine)
    columns = inspector.get_columns('post')
    column_names = [col['name'] for col in columns]
    print("Post表列名:", column_names)
    if 'favorites' in column_names:
        print("✓ Post表包含 favorites 列")
    else:
        print("✗ Post表缺少 favorites 列")
    
    # 验证关联表 post_favorites
    tables = inspector.get_table_names()
    if 'post_favorites' in tables:
        print("✓ post_favorites表存在")
        pf_columns = inspector.get_columns('post_favorites')
        pf_column_names = [col['name'] for col in pf_columns]
        print("post_favorites表列名:", pf_column_names)
    else:
        print("✗ post_favorites表不存在")

print("数据库设置完成") 